<template>
  <div id="layer-tree">
    <!-- <el-tree :data="baseLayerData" @node-click="baseLayerClick"></el-tree> -->
    <el-tree
      :data="data"
      :props="{label:'name'}"
      node-key="id"
      show-checkbox
      :expand-on-click-node="false"
      @node-click="nodeClick"
      ref="LayerManagerTree"
      @check="onCheck"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span class="toolbar" v-if="!readonly">
          <i
            class="el-icon-plus"
            v-if="data.layerType == 'layerGroup'"
            @click="add(data)"
            @click.stop
          ></i>
          <i class="el-icon-edit" @click="editLayer(data)" @click.stop></i>
          <!--v-if="data.dataType !== 'layerGroup'"-->
          <!-- <i class="iconfont iconshuju1"  @click.stop="propertyShow(data)"></i>-->
          <i class="el-icon-delete" @click.stop="deleteLayer(node,data)"></i>
          <i style="display:inline-block;width:10px;height:100%;"></i>
        </span>
      </span>
    </el-tree>
    <el-dialog title="图层管理" :visible.sync="layerMangerDialog" width="45%" append-to-body>
      <el-tabs tabPosition="left" v-model="activeName">
        <el-tab-pane name="layerGroup" label="图层组">
          <layer-group
            :node-data="currentData"
            action-type="add"
            @showDialog="onShowDialog"
            :fresh-tree-data="updateLayer"
          ></layer-group>
        </el-tab-pane>
        <el-tab-pane name="layer" label="图层">
          <layer
            :node-data="currentData"
            action-type="add"
            @showDialog="onShowDialog"
            :fresh-tree-data="updateLayer"
          ></layer>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog title="编辑图层组" :visible.sync="layerGroupDialog" width="300px" append-to-body>
      <layer-group
        :node-data="currentData"
        action-type="edit"
        @showDialog="onShowDialog"
        :fresh-tree-data="updateLayer"
      ></layer-group>
    </el-dialog>
    <el-dialog title="添加图层组" :visible.sync="addLayerGroupDialog" width="300px" append-to-body>
      <layer-group
        :node-data="currentData"
        action-type="add"
        @showDialog="onShowDialog"
        :fresh-tree-data="updateLayer"
      ></layer-group>
    </el-dialog>
    <el-dialog title="编辑图层" :visible.sync="layerDialog" width="400px" append-to-body>
      <layer
        :node-data="currentData"
        action-type="edit"
        @showDialog="onShowDialog"
        :fresh-tree-data="updateLayer"
      ></layer>
    </el-dialog>
  </div>
</template>
<script>
import MapLayerManager from "@/assets/js/map/MapLayerManager";
import baseLayerJson from "@/assets/json/BaseLayers";
import maps from "@/assets/js/map/mapUtils";
import Layer from "./Layer";
import LayerGroup from "./LayerGroup";
import { construct, destruct } from "@aximario/json-tree";
export default {
  name: "LayerManager",
  components: {
    Layer,
    LayerGroup
  },
  mixins: [MapLayerManager],
  props: {
    showEditDialog: {
      type: Boolean,
      default: false,
      require: false
    },
    mapId: {
      type: String,
      default: "mainMap"
    },
    readonly: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  data() {
    return {
      legendArr: [],
      data: [],
      baseLayerData: [],
      layerGroupDialog: false,
      layerDialog: false,
      currentData: {},
      layerMangerDialog: false,
      activeName: "layerGroup",
      addLayerGroupDialog: false
    };
  },
  mounted: function() {
    this.getTreeData();
    this.getBaseLayerData();
  },
  methods: {
    getTreeData() {
      var self = this;
      this.$http
        .getLayerTree()
        .then(res => {
          self.data = construct(res.data.data, {
            id: "id",
            pid: "fid",
            children: "children"
          });
        })
        .catch(err => {
          throw err;
          console.log("获取图层树失败！！！");
        });
    },
    /*
     * 刷新数据
     * */
    updateLayer(data) {
      var node = this.$refs.LayerManagerTree.getNode(data.id);
      if (node) {
        node.data.name = data.name;
        node.data.serverUrl = data.serverUrl;
        node.data.layerIndex = data.layerIndex;
        node.data.layerType = data.layerType;
        node.data.fid = data.fid;
        node.data.layerExtent = data.layerExtent;
      } else {
        if (data.fid == "-1") {
          this.data.push(data);
        } else {
          var parentNode = this.$refs.LayerManagerTree.getNode(data.fid);
          if (!parentNode.data.children) {
            this.$set(parentNode.data, "children", []);
          }
          parentNode.data.children.push(data);
        }
      }
    },
    /*
     * 关闭弹出框
     * */
    onShowDialog(bool) {
      if (this.layerMangerDialog) {
        this.layerMangerDialog = false;
      } else if (this.layerDialog) {
        this.layerDialog = false;
      } else if (this.layerGroupDialog) {
        this.layerGroupDialog = false;
      } else if (this.addLayerGroupDialog) {
        this.addLayerGroupDialog = false;
      }
    },
    /*
     * 当基础图层树节点被选中
     * */
    baseLayerClick(data) {
      if (data.type && data.type == "layerGroup") {
        return;
      }
      var map = maps[this.mapId],
        layer = map.getLayer(data.id);
      if (layer) {
        map.removeLayer(layer);
      } else {
        this.addTileLayer(data, map);
      }
    },
    getBaseLayerData() {
      this.baseLayerData = baseLayerJson;
    },
    //添加按钮
    add(data) {
      this.currentData = data;
      this.layerMangerDialog = true;
    },
    //编辑图层信息
    editLayer(data) {
      this.currentData = data;
      if (data.layerType && data.layerType == "layerGroup") {
        this.layerGroupDialog = true;
      } else {
        this.layerDialog = true;
      }
    },
    //编辑属性信息
    //删除数据
    deleteLayer(node, data) {
      if (data.layerType == "layerGroup") {
        if (data.children && data.children.length > 0) {
          this.delLayerOrGroup(
            "这个图层下有图层,删除将图层组下所有图层删除,是否继续?",
            node,
            data
          );
        } else {
          this.delLayerOrGroup("此操作将图层组永久删除, 是否继续?", node, data);
        }
      } else {
        this.delLayerOrGroup("此操作将图层永久删除, 是否继续?", node, data);
      }
    },
    //删除图层或图层组
    delLayerOrGroup(mesg, node, data) {
      var self = this;
      this.$confirm(mesg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          self.$http
            .delLayer(data.id)
            .then(res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              const parent = node.parent;
              const children = parent.data.children || parent.data;
              const index = children.findIndex(d => d.id === data.id);
              children.splice(index, 1);
            })
            .catch(err => {
              console.log("删除图层失败！！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    /**
     * 当复选框被点击的时候触发
     *共两个参数，依次为：传递给 data 属性的数组中
     * 该节点所对应的对象、树目前的选中状态对象，包
     * 含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
     * */
    onCheck(node, checked) {
      this.mode = "check";
      //获取所有选中的叶子节点
      let checkedLayer = checked.checkedNodes.filter(item => {
        if (!item.children) {
          return true;
        }
      });
      // this.$emit("checkedLayer", checkedLayer);
      this.renderLayer(node, checked);
    },

    renderLayer(node,checked){
        var cheked=checked.checkedKeys.indexOf(node.id)!==-1
        if(node.children && cheked){
          node.children.forEach((child)=>{
            this.addWMSToLayer(child, this.mapId);
            if (child.layerIndex && child.layerIndex != 0) {
              if (this.legendArr.indexOf(child.layerIndex) == -1) {
                this.legendArr.push(child.layerIndex);
              }
            }
          })
        }else if(node.children && !cheked){
          node.children.forEach((child)=>{
            this.removeLayer(child, this.mapId);
            if (child.layerIndex && child.layerIndex != 0) {
              this.legendArr.splice(this.legendArr.indexOf(child.layerIndex), 1);
            }
          })
        }else if(!node.children && cheked){
            this.addWMSToLayer(node, this.mapId);
            if (node.layerIndex && node.layerIndex != 0) {
              if (this.legendArr.indexOf(node.layerIndex) == -1) {
                this.legendArr.push(node.layerIndex);
              }
            }
        }else if(!node.children && !cheked){
            this.removeLayer(node, this.mapId);
            if (node.layerIndex && node.layerIndex != 0) {
              this.legendArr.splice(this.legendArr.indexOf(node.layerIndex), 1);
            }
        }
      },

    /*
     * 树节点选中或取消选中的事件
     * */
    // checkTreeNode(data, treeNode) {
    //   var nodes = this.$refs.LayerManagerTree.getCheckedNodes(true, false);
    //   console.log(nodes);

    //   //先判断是选中还是取消选中
    //   var self = this,
    //     flag = false;
    //   for (var i = 0; i < treeNode.checkedNodes.length; i++) {
    //     if (treeNode.checkedNodes[i].id == data.id) {
    //       flag = true;
    //     }
    //   }
    //   if (flag) {
    //     //添加到地图上
    //     if (data.type && data.children) {
    //       var childrens = [];
    //       this.getChildrens(data, childrens);
    //       for (var i = 0; i < childrens.length; i++) {
    //         if (childrens[i].layerType && childrens[i].layerType == "POI") {
    //           this.$http
    //             .getThematicDataByLayerId(childrens[i].id)
    //             .then(res => {
    //               var datas = res.data.data;
    //               self.addWktLayer(datas, maps[self.mapId], function(grphic) {
    //                 self.layerClickFunction(grphic);
    //               });
    //             })
    //             .catch(err => {
    //               throw err;
    //               console.log("获取基础图层数据！！");
    //             });
    //         } else {
    //           // this.addLayerToMap(data,this.mapId)
    //           this.addWMSToLayer(data, this.mapId);
    //         }
    //       }
    //     } else if (data) {
    //       if (data.layerType && data.layerType == "POI") {
    //         this.$http
    //           .getThematicDataByLayerId(data.id)
    //           .then(res => {
    //             var datas = res.data.data;
    //             self.addWktLayer(datas, maps[self.mapId], function(grphic) {
    //               self.layerClickFunction(grphic);
    //             });
    //           })
    //           .catch(err => {
    //             throw err;
    //             console.log("获取基础图层数据！！");
    //           });
    //       } else {
    //         // this.addLayerToMap(data,this.mapId)
    //         this.addWMSToLayer(data, this.mapId);
    //       }
    //     }
    //   } else {
    //     //从地图上移除data数据图层
    //     if (data.type && data.children) {
    //       var childrens = [];
    //       this.getChildrens(data, childrens);
    //       for (var i = 0; i < childrens.length; i++) {
    //         this.removeLayer(childrens[i], maps[self.mapId]);
    //       }
    //     } else if (data) {
    //       this.removeLayer(data, maps[self.mapId]);
    //     }
    //     this.$emit("layerClick", JSON.stringify({}));
    //   }
    // },
    //当地图上数据被点击后的回调
    layerClickFunction(graphic) {
      this.$emit("layerClick", JSON.stringify(graphic.attributes));
    },
    getChildrens(data, childrens) {
      if (data.children && data.children.length > 0) {
        for (var i = 0; i < data.children.length; i++) {
          if (data.children[i].type && data.children[i].children) {
            this.getChildrens(data.children[i], childrens);
          } else {
            childrens.push(data.children[i]);
          }
        }
      }
    },
    //点击图层定位
    nodeClick(data, treeNode, evt) {
      if (
        treeNode.checked &&
        data.layerType == "dynamicLayer" &&
        data.layerExtent
      ) {
        this.mapExtentForServer(data, this.mapId);
      }
    }
  }
};
</script>
<style scoped lang="scss">
#layer-tree {
  /deep/ .el-tree {
    background-color: transparent;
    color: #11e0ec;
    .custom-tree-node {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .el-tree-node__content {
      background-color: transparent;
      padding-right: 5px;
      font-size: 14px;
      .toolbar {
        opacity: 0;
        transition: all 0.2s;
      }
      .el-tree-node__label {
        font-size: 14px;
      }
      &:hover {
        background-color: rgba(65, 109, 167, 0.6);
        .toolbar {
          opacity: 1;
        }
      }
    }

    .el-checkbox__inner {
      background-color: transparent;
      border: 1px solid #11e0ec;
    }
  }
}
</style>
